package scala.cookbook.akka

import scala.io
import scala.util.{Failure, Success, Try}

/**
  * Created by baiwf on 2017/5/13.
  */
class ch20_UseOptionOften {
  def toInt(s: String): Option[Int] = {
    try {
      Some(Integer.parseInt(s.trim))
    }catch {
      case e: Exception => None
    }
  }

  def readTextFile(filename: String): Option[List[String]] = {
    try {
      Some(io.Source.fromFile(filename).getLines().toList)
    }catch {
      case e:Exception => None
    }
  }

  //如果需要error message而不是Some or None，可使用try/success/failure
  def readTextFile2(filename:String): Try[List[String]] = {
    Try(io.Source.fromFile(filename).getLines().toList)
  }
  def init(): Unit = {
    var filename = "/etc/passwd"
    readTextFile2(filename) match {
      case Success(lines) => lines.foreach(println)
      case Failure(f) => println(f)
    }
  }

  def withCollections(): Unit = {
    val bag = List("1","2","foo","3")
    println(bag.map(toInt))
    println(bag.map(toInt).flatten)//List[Int] = 1,2,3
    bag.flatMap(toInt)
  }
}
